package cn.sjxy.service;

import cn.sjxy.model.Md_LoginUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 封装登录用户保存Redis的相关操作
 */
@Service
public class Sv_Login {

    @Autowired
    private RedisTemplate redisTemplate;

    //将登录的管理员账号保存到Redis中
    public String saveAdmin(String username, String password) throws Exception {

        Md_LoginUser user = new Md_LoginUser();
        user.setUsername(username);
        user.setPassword(password);
        user.setUserType(Md_LoginUser.UserType.admin);

        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(user);
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("UserToken:" + token, jsonStr);
        return token;
    }

    //将登录的用户账号保存到Redis中
    public String saveUser(String username, String password) throws Exception {
        Md_LoginUser user = new Md_LoginUser();
        user.setUsername(username);
        user.setPassword(password);
        user.setUserType(Md_LoginUser.UserType.user);

        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(user);
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("UserToken:" + token, jsonStr);
        return token;
    }

    //从Redis中获取登录的用户
    public Md_LoginUser getLoginUser(String token) throws Exception {
        String jsonStr = redisTemplate.opsForValue().get("UserToken:" + token).toString();
        ObjectMapper mapper = new ObjectMapper();
        Md_LoginUser user = mapper.readValue(jsonStr, Md_LoginUser.class);
        return user;
    }

    //用户退出，从redis中删除
    public void logout(String token) {
        redisTemplate.delete(token);
    }

}



